package com.hyq.learn.api.service;

import com.hyq.learn.api.model.event.EventOne;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;

/**
 * 测试事件发布机制，是同步还是异步，默认情况下，这个过程是同步的，其具体执行逻辑由：SimpleApplicationEventMulticaster 这个默认的事件广播器，
 * 此广播器在执行事件的过程中不会默认不会taskExecutor去执行事件监听任务，只有在明确指定taskExecutor时，才会使用
 *
 * @author heyuqin
 * @date 2025/8/27 17:19
 */
@Service
public class ApplicationEventService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationEventService.class);

    @Autowired
    private ApplicationEventPublisher eventPublisher;

    public void pushEvent(String name) {
        LOGGER.info("event push, event name:{}", name);
        eventPublisher.publishEvent(new EventOne(this, name));
    }

    @EventListener(EventOne.class)
    public void handleEvent(EventOne event) {
        LOGGER.info("event listener, event name:{}", event.getName());
    }
}
